﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HikVisionTool.Helper
{
    public class FileHelper
    {
        private static readonly object LogLock = new object();
        public static void WriteLog(string msg)
        {
            lock (LogLock)
            {
                string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                try
                {
                    using (StreamWriter sw = File.AppendText(logPath))
                    {
                        sw.WriteLine("**************************************************");
                        sw.WriteLine("时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        sw.WriteLine(msg);
                        sw.WriteLine();
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                    }
                }
                catch (IOException e)
                {
                    using (StreamWriter sw = File.AppendText(logPath))
                    {

                        sw.WriteLine("**************************************************");
                        sw.WriteLine("时间：" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
                        sw.WriteLine("异常：" + e.Message);
                        sw.WriteLine();
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                    }
                }
            }
        }
        public static void WriteJson(string jsonstr,string dir,string name)
        {
            lock (LogLock)
            {
                try
                {
                    string path = Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.LastIndexOf('\\')) + "\\离线数据\\" + dir;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string logPath = path + "\\" + name + ".txt";
                    File.WriteAllText(logPath, jsonstr);
                }
                catch (Exception e)
                {
                    FileHelper.WriteLog(e.ToString());
                }
            }
        }
    }
}
